package one.stand.controller.index;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jmp.api.cache.SupplierCacheModel;
import com.jmp.api.cache.SupplierGoodsCacheModel;
import com.jmp.api.dto.*;
import com.jmp.api.util.LabelUtil;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.dto.LiveListRequest;
import com.jmp.base.dto.*;
import com.jmp.feign.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.CommentDto;
import one.stand.dto.Company2Dto;
import one.stand.dto.ConvertUtils;
import one.stand.dto.PageResponse2;
import one.stand.enums.SeeRecordEnums;
import one.stand.mapper.GoodsApiCrmAppMapper;
import one.stand.model.*;
import one.stand.service.*;
import one.stand.util.*;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@Api(description = "店铺页")
@RequestMapping("/supplier")
@RestController
public class SupplierController {

    @Autowired
    private SeeRecordFeign seeRecordFeign;
    @Autowired
    private WebsiteFeign websiteFeign;
    @Autowired
    private RecordFeign recordFeign;
    @Autowired
    private CompanyFeign companyFeign;
    @Autowired
    private LiveFeign liveFeign;
    @Autowired
    private DynamicFeign dynamicFeign;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private WebsiteService websiteService;
    @Autowired
    private RecordPublicService recordPublicService;
    @Autowired
    private GoodsPhotoService goodsPhotoService;
    @Autowired
    private CompanyShowroomService companyShowroomService;
    @Autowired
    private GoodsBaseService goodsBaseService;
    @Autowired
    private BusinessCardBaseService businessCardBaseService;

    @Autowired
    private GoodsApiCrmAppMapper goodsApiCrmAppMapper;

    @ApiOperation(value = "1店铺信息")
    @GetMapping("/info")
    public ResultModel<SupplierInfoResponse> companyInfo(@RequestAttribute SupplierInfoRequest request) {
        AssertUtil.isTrue(Objects.nonNull(request) && Objects.nonNull(request.getCompanyId()), ResultEnum.PARAM_CHECK);

        RequestContext.User user = RequestContextHolder.getRequestContext().getUser();
        final boolean isLogin = Objects.nonNull(user);
        final Integer optUserId = isLogin ? user.getUserId() : null;

        SupplierCacheModel supplierCacheModel = new SupplierCacheModel(redisUtil, request.getCompanyId(), optUserId);
        SupplierInfoResponse response = supplierCacheModel.get();
        if (Objects.isNull(response)) {
            Company2Dto companyModel = companyBaseService.get2(request.getCompanyId());
            AssertUtil.nonNull(companyModel, ResultEnum.NO_DATA, "店铺不存在");
            AssertUtil.isTrue(companyModel.getDelFlag() == 0, ResultEnum.FAIL, "店铺不存在");
            boolean hasZkgx = companyBaseService.hasZkgx(companyModel.getCompanyId());

            //商品分类
            List<GoodsType> goodstypeModelList = goodsApiCrmAppMapper.selectTypes(companyModel.getCompanyId());
            List<SupplierInfoResponse.Type> types = OneListUtil.group(goodstypeModelList,
                    goodsType -> goodsType.getParentId() == 0,
                    GoodsType::getGoodstypeId,
                    GoodsType::getParentId,
                    (parent, child) -> parent.getChildList().add(child),
                    goodsType -> SupplierInfoResponse.Type.builder()
                            .goodsTypeId(goodsType.getGoodstypeId())
                            .name(goodsType.getName())
                            .childList(Lists.newLinkedList())
                            .build(),
                    goodsType -> SupplierInfoResponse.Type.builder()
                            .goodsTypeId(goodsType.getGoodstypeId())
                            .name(goodsType.getName())
                            .build());

            CompanyShowroom companyShowroom = companyShowroomService.getByCompanyId(request.getCompanyId());

            //没有指定名片时取企业名片
            Integer cardId = request.getCardId();
            if (Objects.isNull(cardId)) {
                ResultModel<CompanyCardResponse> cardResponseResultModel = companyFeign.card(CompanyCardRequest.builder().companyId(request.getCompanyId()).build());
                cardId = ConvertUtils.result(cardResponseResultModel, CompanyCardResponse::getCardId);
            }
            //card info
            BusinessCard card = businessCardBaseService.getCustomer(cardId);

            response = SupplierInfoResponse.builder()
                    .companyId(request.getCompanyId())
                    .companyName(companyModel.getCompanyName())
                    .companyLevel(companyModel.countCompanyLevelView())
                    .hasZkgx(BooleanUtils.toInteger(hasZkgx))
                    .goodsTypeList(types)
                    .vrUrl(Objects.nonNull(companyShowroom) ? companyShowroom.getVrUrl() : null)

                    .userId(card.getUserId())
                    .userChatId(String.valueOf(card.getUserId()))
                    .cardId(cardId)
                    .cardName(card.getName())
                    .cardImg(card.getLogo())
                    .position(card.getPosition())
                    .phone(card.getPhone())

                    .build();

            supplierCacheModel.save(response);
        }

        //是否直播中
        com.jmp.base.dto.LiveListRequest liveListRequest = com.jmp.base.dto.LiveListRequest.builder()
                .companyId(request.getCompanyId())
                .build();
        liveListRequest.setPageNum(1);
        liveListRequest.setPageSize(1);
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);
        PageResponse2<LiveListVo.Live> livePage = liveListVoResultModel.getData().getLivePage();
        final boolean isLive = Objects.nonNull(livePage) && OneListUtil.isNotEmpty(livePage.getList()) && livePage.getList().get(0).getStatus() == 1;
        response.setLiveFlag(BooleanUtils.toInteger(isLive));

        //是否收藏
        boolean isCollection = false;
        boolean userCollectFlag = false;
        if (isLogin) {
            isCollection = recordPublicService.isCollection(optUserId, RecordPublicService.ITEMTYPE_COMPANY, request.getCompanyId());
            if (Objects.nonNull(response.getUserId())) {
                userCollectFlag = recordPublicService.isCollection(optUserId, RecordPublicService.ITEMTYPE_USER, response.getUserId());
            }
        }
        response.setCollectFlag(BooleanUtils.toInteger(isCollection));
        response.setUserCollectFlag(BooleanUtils.toInteger(userCollectFlag));

        //营业执照
        ResultModel<CompanyLicenseInfoResponse> licenseInfoResponseResultModel = companyFeign.licenseInfo(CompanyLicenseInfoRequest.builder().companyId(response.getCompanyId()).build());
        response.setLicensePhotosFlag(BooleanUtil.toInteger(StrUtil.isNotBlank(licenseInfoResponseResultModel.getData().getPhotos())));
        response.setLicensePhotos(StrUtil.isNotBlank(licenseInfoResponseResultModel.getData().getPhotos()) ? StrUtil.split(licenseInfoResponseResultModel.getData().getPhotos(), CharUtil.COMMA) : CollUtil.newArrayList());

        return ResultModel.success(response);
    }

    @ApiOperation(value = "1店铺信息-分类")
    @GetMapping("/info/type")
    public ResultModel<SupplierInfoTypeResponse> infoType(@RequestAttribute SupplierInfoRequest request) {
        AssertUtil.isTrue(Objects.nonNull(request) && Objects.nonNull(request.getCompanyId()), ResultEnum.PARAM_CHECK);

        //商品分类
        List<GoodsType> goodstypeModelList = goodsApiCrmAppMapper.selectTypes(request.getCompanyId());
        List<SupplierInfoTypeResponse.Type> types = OneListUtil.group(goodstypeModelList,
                goodsType -> goodsType.getParentId() == 0,
                GoodsType::getGoodstypeId,
                GoodsType::getParentId,
                (parent, child) -> parent.getChildList().add(child),
                goodsType -> SupplierInfoTypeResponse.Type.builder()
                        .typeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .childList(Lists.newLinkedList())
                        .build(),
                goodsType -> SupplierInfoTypeResponse.Type.builder()
                        .typeId(goodsType.getGoodstypeId())
                        .name(goodsType.getName())
                        .build());

        SupplierInfoTypeResponse response = SupplierInfoTypeResponse.builder()
                .types(types)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "1关注| 已废弃,使用【首页-个人主页】")
    @PostMapping("/collect")
    @SecurityAuthCheck
    @Deprecated
    public ResultModel collect(@RequestAttribute SupplierCollectRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();

        ResultModel<RecordCollectionVo> resultModel = recordFeign.collection(RecordCollectionDto.builder()
                .userId(optUser.getUserId())
                .itemType(RecordPublicService.ITEMTYPE_COMPANY)
                .itemId(request.getCompanyId())
                .build());
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "2产品列表")
    @PostMapping("/goods")
    public ResultModel<SupplierGoodsResponse> goods(@RequestAttribute SupplierGoodsRequest request) {
        AssertUtil.nonNull(request.getCompanyId(), ResultEnum.PARAM_CHECK);

        SupplierGoodsCacheModel supplierGoodsCacheModel = new SupplierGoodsCacheModel(redisUtil, request);
        SupplierGoodsResponse resultModel = supplierGoodsCacheModel.get();
        if (Objects.nonNull(resultModel)) return ResultModel.success(resultModel);

        String goodsNameLike = SqlUtil.like(request.getGoodsName());
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Goods> list = goodsApiCrmAppMapper.selectSupplierGoods(request.getGoodstypeId(), request.getCompanyId(), goodsNameLike);
        PageResponse2<SupplierGoodsResponse.Goods> goodsPage = ConvertUtils.page2(list, goodsModel -> {
            boolean hasVr = StringUtils.isNoneBlank(goodsModel.getQjVrUrl());
            boolean hasAr = goodsBaseService.hasAr(goodsModel.getGoodsId());
            boolean hasVideo = StringUtils.isNoneBlank(goodsModel.getVideoUrl());
            boolean hasZkgx = companyBaseService.hasZkgx(goodsModel.getCompanyId());
            String photo = goodsPhotoService.getPath(goodsModel.getGoodsId());
            Long popularityNum = recordPublicService.getPopularity(SeeRecordEnums.PRODUCT.getCode(), goodsModel.getGoodsId());

            return SupplierGoodsResponse.Goods.builder()
                    .goodsId(goodsModel.getGoodsId())
                    .goodsName(goodsModel.getGoodsName())
                    .photo(OneStringUtils.photoResize(photo))
                    .price(goodsModel.getPrice())
                    .labels(LabelUtil.getLabels(hasVr, hasAr, hasVideo, hasZkgx))
                    .popularityNum(popularityNum)
                    .build();
        });
        SupplierGoodsResponse response = SupplierGoodsResponse.builder()
                .goodsPage(goodsPage)
                .build();

        if (request.getPageNum() == 1) {//缓存第一页
            supplierGoodsCacheModel.save(response);

            if (RequestContextHolder.getRequestContext().isLogin() && !RequestContextHolder.getRequestContext().isSameCompany(request.getCompanyId())) {//添加查看记录
                Integer cardId = request.getCardId();
                if (Objects.isNull(cardId)) {
                    ResultModel<CompanyCardResponse> cardResponseResultModel = companyFeign.card(CompanyCardRequest.builder().companyId(request.getCompanyId()).build());
                    cardId = ConvertUtils.result(cardResponseResultModel, CompanyCardResponse::getCardId);
                }
                SeeRecordGoodsListRequest recordGoodsListRequest = SeeRecordGoodsListRequest.builder()
                        .userId(RequestContextHolder.getRequestContext().getUser().getUserId())
                        .cardId(cardId)
                        .build();
                seeRecordFeign.goodsList(recordGoodsListRequest);
            }
        }
        return ResultModel.success(response);
    }

    @ApiOperation(value = "3官网")
    @GetMapping("/website")
    public ResultModel<SupplierWebsiteResponse> getWebsiteInfo(@RequestAttribute SupplierWebsiteRequest request) {
        AssertUtil.nonNull(request.getCompanyId(), ResultEnum.PARAM_CHECK);

        Website model = websiteService.getByCompanyId(request.getCompanyId());
        //视频
        ResultModel<WebsiteVideoVo> resultModel = websiteFeign.video(WebsiteVideoDto.builder().companyId(request.getCompanyId()).build());
        AssertUtil.isTrue(resultModel);
        List<SupplierWebsiteResponse.Video> videoModels = ConvertUtils.list(resultModel.getData().getVideoList(), video -> SupplierWebsiteResponse.Video.builder()
                .url(video.getUrl())
                .describes(video.getDescribes())
                .cover(video.getCover())
                .build());

        //主推商品
        List<Goods> mainPush = goodsApiCrmAppMapper.selectMainPush(request.getCompanyId());
        List<SupplierWebsiteResponse.Goods> mainGoodsList = ConvertUtils.list(mainPush, goods -> SupplierWebsiteResponse.Goods.builder()
                .goodsId(goods.getGoodsId())
                .name(goods.getGoodsName())
                .pic(OneStringUtils.photoResize(goodsPhotoService.getPath(goods.getGoodsId())))
                .build());
        if (OneListUtil.isEmpty(mainGoodsList)) {
            //每日精选
            List<Goods> daySelect = goodsApiCrmAppMapper.selectDaySelect(request.getCompanyId());
            List<SupplierWebsiteResponse.Goods> dayGoodsList = ConvertUtils.list(daySelect, goods -> SupplierWebsiteResponse.Goods.builder()
                    .goodsId(goods.getGoodsId())
                    .name(goods.getGoodsName())
                    .pic(OneStringUtils.photoResize(goodsPhotoService.getPath(goods.getGoodsId())))
                    .build());
            if (OneListUtil.isNotEmpty(dayGoodsList)) {
                mainGoodsList = dayGoodsList.size() > 3 ? dayGoodsList.subList(0, 3) : dayGoodsList;
            }
        }

        SupplierWebsiteResponse websiteResponse = SupplierWebsiteResponse.builder()
                .photos(model.getPhotos())
                .companyIntroduce(model.getCompanyIntroduce())
                .goodsIntroduce(model.getGoodsIntroduce())
                .address(model.getAddress())
                .latitude(model.getLatitude())
                .longitude(model.getLongitude())
                .phone(model.getPhone())
                .companyVideoModelList(videoModels)
                .mainGoodsList(mainGoodsList)
                .build();

        RequestContext requestContext = RequestContextHolder.getRequestContext();
        if (requestContext.isLogin() && !requestContext.isSameCompany(request.getCompanyId())) {//添加查看记录
            Integer cardId = request.getCardId();
            if (Objects.isNull(cardId)) {
                ResultModel<CompanyCardResponse> cardResponseResultModel = companyFeign.card(CompanyCardRequest.builder().companyId(request.getCompanyId()).build());
                cardId = ConvertUtils.result(cardResponseResultModel, CompanyCardResponse::getCardId);
            }
            SeeRecordWebsiteRequest recordWebsiteRequest = SeeRecordWebsiteRequest.builder()
                    .userId(requestContext.getUser().getUserId())
                    .cardId(cardId)
                    .companyId(request.getCompanyId())
                    .itemId(model.getWebsiteId())
                    .build();
            seeRecordFeign.website(recordWebsiteRequest);
        }

        return ResultModel.success(websiteResponse);
    }

    @ApiOperation(value = "3官网：用户提交需求信息")
    @PostMapping("/demand")
    @SecurityAuthCheck
    public ResultModel demand(@RequestAttribute SupplierDemandRequest request) {

        ResultModel<CompanyCardResponse> cardResponseResultModel = companyFeign.card(CompanyCardRequest.builder().companyId(request.getCompanyId()).build());
        AssertUtil.isTrue(cardResponseResultModel);
        final Integer companyCardId = cardResponseResultModel.getData().getCardId();

        WebsiteDemandSaveDto saveDto = WebsiteDemandSaveDto.builder()
                .cardId(companyCardId)
                .name(request.getName())
                .phone(request.getPhone())
                .text(request.getText())
                .optUserId(RequestContextHolder.getRequestContext().getUser().getUserId())
                .build();
        ResultModel resultModel = websiteFeign.demandSave(saveDto);
        AssertUtil.isTrue(resultModel);

        return ResultModel.success();
    }

    @ApiOperation(value = "4动态：直播", notes = "播放接口 请查看【首页-直播:观看直播】下相关接口")
    @GetMapping("live")
    @Deprecated
    public ResultModel<SupplierLiveResponse> list(@RequestAttribute com.jmp.api.dto.SupplierLiveRequest request) {

        AssertUtil.nonNull(request.getCompanyId(), ResultEnum.PARAM_CHECK);

        LiveListRequest liveListRequest = LiveListRequest.builder()
                .companyId(request.getCompanyId())
                .build();
        liveListRequest.setPageNum(request.getPageNum());
        liveListRequest.setPageSize(request.getPageSize());
        ResultModel<LiveListVo> liveListVoResultModel = liveFeign.list(liveListRequest);
        AssertUtil.isTrue(liveListVoResultModel);

        PageResponse2<SupplierLiveResponse.Live> livePage = ConvertUtils.page2(liveListVoResultModel.getData().getLivePage(), live -> {
            return SupplierLiveResponse.Live.builder()
                    .roomId(live.getRoomId())
                    .photo(live.getPhoto())
                    .status(LabelUtil.getLiveStatus(live.getStatus()))
                    .viewNum(live.getViewNum() + "人观看")//直播中才显示观看人数
                    .time(live.getTime().getTime())
                    .build();
        });

        SupplierLiveResponse response = SupplierLiveResponse.builder()
                .livePage(livePage)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "4动态：文章", notes = "点赞、回复、分享等接口 请查看【首页-红木圈】下相关接口")
    @GetMapping("/dynamic")
    public ResultModel<SupplierDynamicResponse> dynamic(@RequestAttribute SupplierDynamicRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        final boolean isLogin = Objects.nonNull(optUser);

        DynamicListDto dynamicListDto = DynamicListDto.builder()
                .companyId(request.getCompanyId())
                .build();
        dynamicListDto.setPageNum(request.getPageNum());
        dynamicListDto.setPageSize(request.getPageSize());
        ResultModel<DynamicListVo> resultModel = dynamicFeign.list(dynamicListDto);
        AssertUtil.isTrue(resultModel);

        PageResponse2<SupplierDynamicResponse.Dynamic> dynamicPageResponse2 = ConvertUtils.page2(resultModel.getData().getDynamics(), dynamic -> {

            //最早三条评论
            List<CommentDto> commentDtos = recordPublicService.getCommentList(dynamic.getDynamicId(), 3);
            List<SupplierDynamicResponse.Comment> commentResponseList = ConvertUtils.list(commentDtos, commentModel -> {
                return SupplierDynamicResponse.Comment.builder()
                        .userName(commentModel.getUserName())
                        .content(commentModel.getText())
                        .build();
            });

            boolean isThumbs = isLogin && recordPublicService.isThumbs(optUser.getUserId(), RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId());

            return SupplierDynamicResponse.Dynamic.builder()
                    .dynamicId(dynamic.getDynamicId())

                    .time(dynamic.getTime())
                    .type(dynamic.getType())
                    .title(dynamic.getTitle())
                    .photos(dynamic.getPhotos())

                    .commentNum(recordPublicService.countCommentByDynamic(dynamic.getDynamicId()))
                    .doThumbsNum(recordPublicService.getThumbsCount(RecordPublicService.THUMBS_TYPE_ARTICLE, dynamic.getDynamicId()))
                    .thumbsFlag(BooleanUtils.toInteger(isThumbs))

                    .commentList(commentResponseList)
                    .build();
        });

        SupplierDynamicResponse response = SupplierDynamicResponse.builder()
                .dynamics(dynamicPageResponse2)
                .build();
        return ResultModel.success(response);
    }
}
